package com.wf.course.web.Interceptor;

import java.lang.reflect.Method;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.utils.dateUtil.DateUtil;
import com.wf.course.model.log.SysOperateLog;
import com.wf.course.model.user.User;
import com.wf.course.service.impl.ISysOperateLogServiceImpl;
import com.wf.course.web.Constants;

@Component
@Aspect
public class SystemLogAspect {
	//本地日志对象
	private static final Logger logger = LoggerFactory.getLogger(SystemLogAspect.class);
	
	@Autowired
	private ISysOperateLogServiceImpl logService;
	
	  //controller层切点
    @Pointcut("@annotation(com.wf.course.web.Interceptor.LogInfo)")
    public void controllerAspect(){}
	
	@Before("controllerAspect()")
	public void doBefore(JoinPoint joinPoint) throws ClassNotFoundException, IllegalArgumentException, IllegalAccessException, InstantiationException{
		HttpServletRequest request=((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		Object token = request.getSession().getAttribute("login_token");
		if(token != null){
			User user = Constants.LOGIN_USER.get(token.toString());
			
			//目标类名称
			String className = joinPoint.getTarget().getClass().getName();
			//方法名
			String methodName = joinPoint.getSignature().getName();
			//参数数组
			Object[] arguments = joinPoint.getArgs();
			//参数名称数组
			String[] argsName = getArgsName(className, methodName, arguments);
			
			StringBuilder args = new StringBuilder();
			try {
				for (int i = 0; i < argsName.length; i++) {
					args.append(args.toString().length()>0 ? ","+argsName[i]+":"+arguments[i] : argsName[i]+":"+arguments[i]);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
//			for (Object object : arguments) {
//				args.append(args.toString().length()>0 ? ","+object : object);
//			}
			
			//注解值
			String value = getValue(className,methodName,arguments);
			String time = DateUtil.dateToString1(new Date());
			
			try {
				logService.insert(new SysOperateLog(0, user.getUserName(), user.getId(), value, className, methodName, args.toString(), time));
			} catch (Exception e) {
				e.printStackTrace();
				 logger.error("异常信息:{}", e.getMessage());    
			}
		}
	}

	private String getValue(String className, String methodName, Object[] arguments){
		String value="";
		try {
			Class targetClass = Class.forName(className);
			Method[] methods = targetClass.getMethods();
			
			for (Method method : methods) {
				if(method.getName()==methodName){
					Class[] methodType = method.getParameterTypes();
					if(methodType.length==arguments.length){
						value = method.getAnnotation(LogInfo.class).value();
						break;
					}
				}
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return value;
	}
	//参数列表名称
	@SuppressWarnings("unused")
	private String[] getArgsName(String className, String methodName, Object[] arguments){
		String argsName[] = null;
		LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();  
		try {
			Class targetClass = Class.forName(className);
			Method[] methods = targetClass.getMethods();
			
			for (Method method : methods) {
				if(method.getName()==methodName){
					Class[] methodType = method.getParameterTypes();
					if(methodType.length==arguments.length){
						argsName = u.getParameterNames(method);  
						break;
					}
				}
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return argsName;
	}

}
